package com.dream21th.admin.controller;

import com.dream21th.admin.entity.SysRoleEntity;
import com.dream21th.admin.service.SysRoleMenuService;
import com.dream21th.admin.service.SysRoleService;
import com.dream21th.admin.utils.Constant;
import com.dream21th.admin.utils.PageUtils;
import com.dream21th.common.ComResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseUserController{
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;

	/**
	 * 角色列表
	 */
	@PostMapping("/list")
	public ComResp<PageUtils> list(@RequestParam Map<String, Object> params, Authentication authentication){
		Long loginUserId = loginUserId(authentication);
		//如果不是超级管理员，则只查询自己创建的角色列表
		if(loginUserId != Constant.SUPER_ADMIN){
			params.put("createUserId", loginUserId);
		}
		PageUtils page = sysRoleService.queryPage(params);
		return new ComResp<PageUtils>().data(page).success();
	}

	/**
	 * 角色列表
	 */
	@PostMapping("/select")
	public ComResp<List<SysRoleEntity>> select(Authentication authentication){
		Map<String, Object> map = new HashMap<>();
		Long loginUserId = loginUserId(authentication);
		//如果不是超级管理员，则只查询自己所拥有的角色列表
		if(loginUserId != Constant.SUPER_ADMIN){
			map.put("create_user_id", loginUserId);
		}
		List<SysRoleEntity> list = (List<SysRoleEntity>) sysRoleService.listByMap(map);
		return new ComResp<List<SysRoleEntity>>().data(list).success();
	}

	/**
	 * 角色信息
	 */
	@PostMapping("/infoByRoleId")
	public ComResp info(@RequestBody SysRoleEntity sysRoleEntity){
		SysRoleEntity role = sysRoleService.getById(sysRoleEntity.getRoleId());

		//查询角色对应的菜单
		List<Long> menuIdList = sysRoleMenuService.queryMenuIdList(sysRoleEntity.getRoleId());
		role.setMenuIdList(menuIdList);

		return new ComResp().data(role).success();
	}

	/**
	 * 保存角色
	 */
	@PostMapping("/save")
	public ComResp save(@RequestBody SysRoleEntity role,Authentication authentication){

		role.setCreateUserId(loginUserId(authentication));
		sysRoleService.saveRole(role);

		return new ComResp().success();
	}

	/**
	 * 修改角色
	 */
	@PostMapping("/update")
	public ComResp update(@RequestBody SysRoleEntity role,Authentication authentication){

		role.setCreateUserId(loginUserId(authentication));
		sysRoleService.update(role);

		return new ComResp().success();
	}

	/**
	 * 删除角色
	 */
	@PostMapping("/delete")
	public ComResp delete(@RequestBody Long[] roleIds){
		sysRoleService.deleteBatch(roleIds);

		return new ComResp().success();
	}
}
